package ferp.android.social.twvk;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import ferp.android.R;
import ferp.core.game.Game;
import ferp.core.log.Log;

/**
 * User: olegs
 * Date: 5/14/13 9:40 AM
 */
public abstract class LoginActivity extends Activity
{
  final static String BUNDLE_ACCOUNT = "account";

  @Override
  protected void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.social_login);

    WebView webview = (WebView) findViewById(R.id.twvk_webview);
    webview.getSettings().setJavaScriptEnabled(true);
    webview.clearCache(true);

    webview.setWebViewClient(new SocialWebViewClient());

    // for Vk cookies must be cleared
    // for Tw cookies are left as is
    handleCookie();

    String url = getAuthUrl();

    if (url == null)
      finish();
    else
      webview.loadUrl(url);
  }

  protected void handleCookie() {}

  protected abstract String getTag();

  protected abstract String getAuthUrl();

  protected abstract Account parseRedirectUrl(String url) throws Exception;

  protected abstract String getUrlPrefix();

  private final class SocialWebViewClient extends WebViewClient
  {
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon)
    {
      super.onPageStarted(view, url, favicon);

      parseUrl(url);
    }
  }

  private void parseUrl(String url)
  {
    try
    {
      if (url != null && url.startsWith(getUrlPrefix()) && account == null)
      {
        if(!url.contains("error="))
        {
          account = parseRedirectUrl(url);

          Intent intent = new Intent();
          Bundle b = new Bundle();

          b.putString(BUNDLE_ACCOUNT, Game.gson.toJson(account));
          intent.putExtras(b);

          setResult(Activity.RESULT_OK, intent);
        }

        finish();
      }
    }
    catch (Exception e)
    {
      Log.error(getTag(), e);
    }
  }

  private Account account;
}